// 我是cart模块中的
const state = {
  cartproducts: JSON.parse(window.sessionStorage.getItem('cartdata')) || []
}

const mutations = {
  delcartproducts (state, id) {
    state.cartproducts.filter((item, index) => {
      if (item.id === id) {
        return state.cartproducts.splice(index, 1)
      }
    })
  },
  addcartproducts (state, product) {
    let prod = null
    state.cartproducts.forEach(item => {
      if (item.id === product.id) {
        prod = item
      }
    })
    if (prod) {
      prod.count++
    } else {
      state.cartproducts.push({
        ...product,
        count: 1,
        isChecked: true
      })
    }
  },
  updateproductscount (state, { productID, count }) {
    state.cartproducts.forEach(item => {
      if (item.id === productID) {
        item.count = count
      }
    })
  },
  updateproductschecked (state, { productID, checked }) {
    state.cartproducts.forEach(item => {
      if (item.id === productID) {
        item.isChecked = checked
      }
    })
  },
  toggleallchecked (state, checked) {
    state.cartproducts.forEach(item => {
      item.isChecked = checked
    })
  }
}
const getters = {
  totalCount (state) {
    return state.cartproducts.reduce((quantity, item) => quantity + item.count, 0)
  },
  totalPrice (state) {
    return state.cartproducts.reduce((price, item) => price + (item.count * item.price), 0)
  },
  checkedtotalCoun (state) {
    let count = 0
    state.cartproducts.forEach(item => {
      if (item.isChecked) {
        count += item.count
      }
    })
    return count
  },
  checkedtotalPrice (state) {
    let price = 0
    state.cartproducts.forEach(item => {
      if (item.isChecked) {
        price += (item.count * item.price)
      }
    })
    return price
  }
}
const actions = {

}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions

}
